﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Xml.Linq;
using System.Diagnostics;

namespace Portfolio_Tracker
{
    public partial class MainForm : Form
    {

        #region Variables

        // Currently nothing in here
        //private NotifyIcon notifyIcon1;
        //notifyIcon1.Icon = resources.GetObject("currency_dollar_green_.ico")));

        #endregion

        #region Initilization

        public MainForm()
        {
            InitializeComponent();
        }

        // Main Form Loading Event
        private void MainForm_Load(object sender, EventArgs e)
        {

            // Create folder structure for storing data
            createFolderStructure();

            // Opens account totals file
            openAccountTotalsFiles();

            // Opens Holdings File
            openHoldingsFile();

            // Checking for Internet Connection
            if (!CheckForInternetConnection())
            {
                MessageBox.Show("No internet connection detected.");
                return;
            }

            // Download the watch list information first
            downloadWatchListStockQuotes();

            // Downloads Portfolio Stock Information
            downloadPortfolioStockQuotes();

            // Calculate Totals for portfolio datagridview
            calculateTotals();

            // Starting timer
            SetTimer();

            // Changing last update label
            if (DateTime.Now.Hour > 12)
                lastUpdateLabel.Text = DateTime.Now.ToString("HH:mm:ss") + " PM";
            else
                lastUpdateLabel.Text = DateTime.Now.ToString("HH:mm:ss") + " AM";
        }

        #endregion

        #region Downloading Stock Information from Yahoo API

        /// <summary>
        /// Downloads the stock information from our portfolio data grid view
        /// </summary>
        private void downloadPortfolioStockQuotes()
        {
            
            string beginDownloadURL = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20("; // EX:  http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote%20where%20symbol%20in%20(%22FTT.TO%22)&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys
            string middleDownloadURL = "";
            string endURL = ")&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";

            for (int i = 0; i < portfolioDataGridView.Rows.Count; i++)
            {
                if (portfolioDataGridView.Rows[i].Cells[0].Value.ToString() != "CASH")
                    middleDownloadURL += "%22" + portfolioDataGridView.Rows[i].Cells[0].Value.ToString() + "%22%2C"; 
            }

            middleDownloadURL = middleDownloadURL.Substring(0, middleDownloadURL.Count() - 3);

            XDocument doc = XDocument.Load(beginDownloadURL + middleDownloadURL + endURL);

            XElement results = doc.Root.Element("results");

            for (int i = 0; i < portfolioDataGridView.Rows.Count; i++)
            {
                if (portfolioDataGridView.Rows[i].Cells[0].Value.ToString() != "CASH")
                {
                    try
                    {
                        XElement q = results.Elements("quote").First(w => w.Attribute("symbol").Value == portfolioDataGridView.Rows[i].Cells[0].Value.ToString());

                        if (q.Element("Name").Value.ToString() == portfolioDataGridView.Rows[i].Cells[0].Value.ToString())
                            throw new System.ArgumentException("Invalid ticker");

                        // Name
                        portfolioDataGridView.Rows[i].Cells[1].Value = q.Element("Name").Value;
                        // Last Traded Price
                        portfolioDataGridView.Rows[i].Cells[3].Value = GetDouble(q.Element("LastTradePriceOnly").Value);
                        // Market Value
                        portfolioDataGridView.Rows[i].Cells[7].Value = GetDouble(portfolioDataGridView.Rows[i].Cells[2].Value.ToString()) * GetDouble(q.Element("LastTradePriceOnly").Value);
                        // Daily Change ($)
                        portfolioDataGridView.Rows[i].Cells[4].Value = GetDouble(q.Element("Change").Value);
                        // Daily Change (%)
                        portfolioDataGridView.Rows[i].Cells[5].Value = GetDouble(q.Element("PercentChange").Value)/100;
                        // Unrealized Gain $
                        portfolioDataGridView.Rows[i].Cells[8].Value = GetDouble(portfolioDataGridView.Rows[i].Cells[7].Value.ToString()) - GetDouble(portfolioDataGridView.Rows[i].Cells[6].Value.ToString());
                        // Unrealized Gain %
                        portfolioDataGridView.Rows[i].Cells[9].Value = (GetDouble(portfolioDataGridView.Rows[i].Cells[7].Value.ToString()) / GetDouble(portfolioDataGridView.Rows[i].Cells[6].Value.ToString())) - 1;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error while fetching stock information for " + portfolioDataGridView.Rows[i].Cells[0].Value.ToString() + ": " + ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        portfolioDataGridView.Rows.RemoveAt(i);
                    }
                }

            }

            #region Legacy Code
            //(%22FTT.TO%22%2C%22GIB-A.TO%22)

            // http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote%20where%20symbol%20in%20&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys

            //List<string> stockSymbols = new List<string>();

            //for (int i = 0; i < portfolioDataGridView.Rows.Count; i++)
            //{
            //    if (portfolioDataGridView.Rows[i].Cells[0].Value.ToString() != "CASH")
            //        stockSymbols.Add(portfolioDataGridView.Rows[i].Cells[0].Value.ToString());
            //}

            //string csvFileLocation = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Data", "Stock Quotes", "Stock Quotes - Portfolio.csv");

            //string beginDownloadURL = "http://download.finance.yahoo.com/d/quotes.csv?s="; // EX: http://download.finance.yahoo.com/d/quotes.csv?s=FTT.TO&f=l1p2&e=.csv
            //string middleDownloadURL = "";
            //string endURL = "&f=n0l1p2c6&e=.csv";

            //foreach (string symb in stockSymbols)
            //{
            //    middleDownloadURL += symb + ",";
            //}

            //try
            //{
            //    using (WebClient webClient = new WebClient())
            //    {
            //        webClient.DownloadFile(beginDownloadURL + middleDownloadURL + endURL, csvFileLocation);
            //    }
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message);
            //}

            //char[] delimiterChars = { ',', '\n' };

            //// Reading info from .csv
            //var contents = File.ReadAllText(csvFileLocation).Split(delimiterChars);

            //// Setting starting position of .csv file for portfolio information
            //int startingPostion = 0;

            //for (int i = 0; i < portfolioDataGridView.Rows.Count; i++)
            //{
            //    // If second entry in .csv is 0, no stock information was found
            //    if (contents[startingPostion + 1] == "0.00")
            //    {
            //        MessageBox.Show("No information found for " + contents[startingPostion].ToString().Substring(1, contents[startingPostion].Length - 2) + ".", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //        for (int j = 0; j < portfolioDataGridView.Rows.Count; j++)
            //        {
            //            if (portfolioDataGridView.Rows[j].Cells[0].Value.ToString() == contents[startingPostion].ToString().Substring(1, contents[startingPostion].Length - 2))
            //                portfolioDataGridView.Rows.RemoveAt(j);
            //        }
            //        if (startingPostion + 4 < contents.Length)
            //            startingPostion += 4;
            //        continue;
            //    }
            //    try
            //    {
            //        if (portfolioDataGridView.Rows[i].Cells[0].Value.ToString() != "CASH")
            //        {
            //            double sharePrice, dailyChangePercent, dailyChangeDollar, numOfShares, bookValue;

            //            // Name
            //            portfolioDataGridView.Rows[i].Cells[1].Value = contents[startingPostion].Substring(1, contents[startingPostion].Length - 2);
            //            // Share Price
            //            if (Double.TryParse(contents[startingPostion + 1], out sharePrice))
            //                portfolioDataGridView.Rows[i].Cells[3].Value = sharePrice;
            //            // Daily Change ($)
            //            if (Double.TryParse(contents[startingPostion + 3].Substring(1, contents[startingPostion + 2].Length - 3), out dailyChangeDollar))
            //                portfolioDataGridView.Rows[i].Cells[4].Value = dailyChangeDollar;
            //            // Daily Change (%)
            //            if (Double.TryParse(contents[startingPostion + 2].Substring(1, contents[startingPostion + 2].Length - 3), out dailyChangePercent))
            //                portfolioDataGridView.Rows[i].Cells[5].Value = dailyChangePercent + "%";
            //            // Market Value
            //            if (Double.TryParse(portfolioDataGridView.Rows[i].Cells[2].Value.ToString(), out numOfShares) && Double.TryParse(contents[startingPostion + 1], out sharePrice))
            //                portfolioDataGridView.Rows[i].Cells[7].Value = numOfShares * sharePrice;
            //            // Unrealized Gain $
            //            if (Double.TryParse(portfolioDataGridView.Rows[i].Cells[6].Value.ToString(), out bookValue) && Double.TryParse(portfolioDataGridView.Rows[i].Cells[2].Value.ToString(), out numOfShares) && Double.TryParse(contents[startingPostion + 1], out sharePrice))
            //                portfolioDataGridView.Rows[i].Cells[8].Value = (numOfShares * sharePrice) - bookValue;
            //            // Unrealized Gain %
            //            if (Double.TryParse(portfolioDataGridView.Rows[i].Cells[6].Value.ToString(), out bookValue) && Double.TryParse(portfolioDataGridView.Rows[i].Cells[2].Value.ToString(), out numOfShares) && Double.TryParse(contents[startingPostion + 1], out sharePrice))
            //                portfolioDataGridView.Rows[i].Cells[9].Value = Math.Round((((numOfShares * sharePrice) - bookValue) / bookValue) * 100, 2) + "%";
            //        }
            //        if (startingPostion + 4 < contents.Length)
            //            startingPostion += 4;
            //    }
            //    catch (Exception ex)
            //    {
            //        MessageBox.Show(ex.ToString());
            //    }
            //}

            //double sharePrice, dailyChangeDollar, numOfShares, bookValue, marketValue;

            //// Name
            //portfolioDataGridView.Rows[i].Cells[1].Value = q.Element("Name").Value;
            //// Last Traded Price
            //if (Double.TryParse(q.Element("LastTradePriceOnly").Value, out sharePrice))
            //    portfolioDataGridView.Rows[i].Cells[3].Value = sharePrice;
            //// Market Value
            //if (Double.TryParse(portfolioDataGridView.Rows[i].Cells[2].Value.ToString(), out numOfShares) && Double.TryParse(q.Element("LastTradePriceOnly").Value, out sharePrice))
            //    portfolioDataGridView.Rows[i].Cells[7].Value = numOfShares * sharePrice;
            //// Daily Change ($)
            //if (Double.TryParse(q.Element("Change").Value, out dailyChangeDollar))
            //{
            //    portfolioDataGridView.Rows[i].Cells[4].Value = dailyChangeDollar;
            //}
            //// Daily Change (%)
            //portfolioDataGridView.Rows[i].Cells[5].Value = q.Element("PercentChange").Value;
            //// Unrealized Gain $
            //if (Double.TryParse(portfolioDataGridView.Rows[i].Cells[6].Value.ToString(), out bookValue) && Double.TryParse(portfolioDataGridView.Rows[i].Cells[7].Value.ToString(), out marketValue))
            //    portfolioDataGridView.Rows[i].Cells[8].Value = marketValue - bookValue;
            //// Unrealized Gain %
            //if (Double.TryParse(portfolioDataGridView.Rows[i].Cells[6].Value.ToString(), out bookValue) && Double.TryParse(portfolioDataGridView.Rows[i].Cells[2].Value.ToString(), out numOfShares) && Double.TryParse(portfolioDataGridView.Rows[i].Cells[7].Value.ToString(), out marketValue))
            //    portfolioDataGridView.Rows[i].Cells[9].Value = (marketValue / bookValue) - 1;
            #endregion
        }

        /// <summary>
        /// Downloads watch list information from the Yahoo API
        /// </summary>
        private void downloadWatchListStockQuotes()
        {
            watchListDataGridView.Rows.Clear();

            string beginDownloadURL = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20("; // EX:  http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote%20where%20symbol%20in%20(%22FTT.TO%22)&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys
            string middleDownloadURL = "";
            string endURL = ")&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
            string watchListFileLocation = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Data", "Watch List", "WatchList.csv");

            var watchListContents = File.ReadAllText(watchListFileLocation).Split(',');

            for (int i = 0; i < watchListContents.Count(); i++)
            {
                middleDownloadURL += "%22" + watchListContents[i] + "%22%2C";
            }

            middleDownloadURL = middleDownloadURL.Substring(0, middleDownloadURL.Count() - 3);

            XDocument doc = XDocument.Load(beginDownloadURL + middleDownloadURL + endURL);

            XElement results = doc.Root.Element("results");

            foreach (string stock in watchListContents)
            {
                try
                {
                    XElement q = results.Elements("quote").First(w => w.Attribute("symbol").Value == stock);
                    watchListDataGridView.Rows.Add(stock, q.Element("Name").Value, GetDouble(q.Element("PreviousClose").Value), GetDouble(q.Element("LastTradePriceOnly").Value), GetDouble(q.Element("Change").Value), GetDouble(q.Element("PercentChange").Value)/100, "News", "Charts");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error while fetching stock information for " + stock + " in watch list: " + ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    for (int i = 0; i < watchListDataGridView.Rows.Count; i++)
                    {
                        if (watchListDataGridView.Rows[i].Cells[0].Value.ToString() == stock)
                            portfolioDataGridView.Rows.RemoveAt(i);
                    }
                }
            }

            #region Legacy Code
            //string stocksInfoFileLocation = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Data", "Stock Quotes", "Stock Quotes - Watch List.csv");
            //string watchListFileLocation = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Data", "Watch List", "WatchList.csv");

            //if (!File.Exists(watchListFileLocation))
            //{
            //    MessageBox.Show("No watch list file found.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    return;
            //}

            //try
            //{

            //    var watchListContents = File.ReadAllText(watchListFileLocation).Split(',');

            //    string beginDownloadURL = "http://download.finance.yahoo.com/d/quotes.csv?s="; // EX: http://download.finance.yahoo.com/d/quotes.csv?s=FTT.TO&f=l1p2&e=.csv
            //    string middleDownloadURL = "";
            //    string endURL = "&f=snpl1c6p2&e=.csv";

            //    for (int i = 0; i < watchListContents.Count(); i++)
            //    {
            //        if (i != watchListContents.Count() - 1 && watchListContents[i] != "GIB-A.TO")
            //            middleDownloadURL += watchListContents[i] + ",";
            //        else if (watchListContents[i] != "GIB-A.TO")
            //            middleDownloadURL += watchListContents[i];
            //        else // Special case for GIB-A
            //        {
            //            using (WebClient webClient = new WebClient())
            //            {
            //                webClient.DownloadFile("http://download.finance.yahoo.com/d/quotes.csv?s=GIB-A.TO&f=snpl1c6p2&e=.csv", stocksInfoFileLocation);
            //            }

            //            var GIBContents = File.ReadAllText(stocksInfoFileLocation).Split(',');

            //            double lastClosingPrice, currentPrice, changeDollar, changePercent;

            //            //int startingPosition = 0;

            //            // Last Closing Price
            //            Double.TryParse(GIBContents[3], out lastClosingPrice);
            //            // Current Price
            //            Double.TryParse(GIBContents[4], out currentPrice);
            //            // Change ($)
            //            Double.TryParse(GIBContents[5].Substring(1, GIBContents[5].Length - 2), out changeDollar);
            //            // Change (%)
            //            Double.TryParse(GIBContents[6].Substring(1, GIBContents[6].Length - 6), out changePercent);

            //            watchListDataGridView.Rows.Add(GIBContents[0].Substring(1, GIBContents[0].Length - 2), GIBContents[1].Substring(1, GIBContents[1].Length - 1), lastClosingPrice, currentPrice, changeDollar, changePercent + "%", "News", "Chart");

            //        }
            //    }

            //    using (WebClient webClient = new WebClient())
            //    {
            //        webClient.DownloadFile(beginDownloadURL + middleDownloadURL + endURL, stocksInfoFileLocation);
            //    }
            //}

            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message);
            //}

            //char[] delimiterChars = { ',', '\n' };

            //// Reading info from .csv
            //var stockListContents = File.ReadAllText(stocksInfoFileLocation).Split(delimiterChars);

            //// Setting starting position of .csv file for portfolio information
            //int startingPostion = 0;

            //while (startingPostion + 6 < stockListContents.Length)
            //{
            //    try
            //    {
            //        double lastClosingPrice, currentPrice, changeDollar, changePercent;

            //        // Last Closing Price
            //        Double.TryParse(stockListContents[startingPostion + 2], out lastClosingPrice);
            //        // Current Price
            //        Double.TryParse(stockListContents[startingPostion + 3], out currentPrice);
            //        // Change ($)
            //        Double.TryParse(stockListContents[startingPostion + 4].Substring(1, stockListContents[startingPostion + 4].Length - 2), out changeDollar);
            //        // Change (%)
            //        Double.TryParse(stockListContents[startingPostion + 5].Substring(1, stockListContents[startingPostion + 5].Length - 4), out changePercent);

            //        watchListDataGridView.Rows.Add(stockListContents[startingPostion].Substring(1, stockListContents[startingPostion].Length - 2), stockListContents[startingPostion + 1].Substring(1, stockListContents[startingPostion].Length - 2), lastClosingPrice, currentPrice, changeDollar, changePercent + "%", "News", "Chart");

            //        startingPostion += 6;

            //    }
            //    catch (Exception ex)
            //    {
            //        MessageBox.Show(ex.ToString());
            //        return;
            //    }
            //}
            #endregion
        }

        #endregion

        #region Folder/File Setup

        /// <summary>
        /// Creates the folder structure the program usese to store the CSV files
        /// </summary>
        private void createFolderStructure()
        {
            string dataFolder = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Data");
            string stockQuotesFolder = Path.Combine(dataFolder, "Stock Quotes");
            string accountsFolder = Path.Combine(dataFolder, "Account Files");
            string watchListFolder = Path.Combine(dataFolder, "Watch List");
            string newsListFolder = Path.Combine(dataFolder, "News List");

            /*      FOLDERS         */
            // Data Folder
            if (!Directory.Exists(dataFolder))
                Directory.CreateDirectory(dataFolder);
            // Accounts Folder
            if (!Directory.Exists(accountsFolder))
            {
                Directory.CreateDirectory(accountsFolder);
            }
            // Watch List Folder
            if (!Directory.Exists(watchListFolder))
            {
                Directory.CreateDirectory(watchListFolder);
                File.CreateText(Path.Combine(watchListFolder, "WatchList.csv"));
            }
            // News List Folder
            if (!Directory.Exists(newsListFolder))
                Directory.CreateDirectory(newsListFolder);
            else
            {
                // Delete all old news files
                foreach (string fileName in Directory.GetFiles(newsListFolder))
                    File.Delete(fileName);
            }
            /*      .CSV Files        */
            // Accout Totals File
            if (!File.Exists(Path.Combine(accountsFolder, "AccountTotals.csv")))
                File.CreateText(Path.Combine(accountsFolder, "AccountTotals.csv"));
            // TFSA Totals File
            if (!File.Exists(Path.Combine(accountsFolder, "TFSATotals.csv")))
                File.CreateText(Path.Combine(accountsFolder, "TFSATotals.csv"));
            // RRSP Totals File
            if (!File.Exists(Path.Combine(accountsFolder, "RRSPTotals.csv")))
                File.CreateText(Path.Combine(accountsFolder, "RRSPTotals.csv"));
            // Holdings File
            if (!File.Exists(Path.Combine(accountsFolder, "Holdings.csv")))
                File.CreateText(Path.Combine(accountsFolder, "Holdings.csv"));
            
        }

        #endregion

        #region Formatting DataGridViews

        /// <summary>
        /// Updates font colors in datagridviews
        /// </summary>
        private void updateFontColors()
        {
            if (portfolioDataGridView.Rows.Count > 1)
            {
                for (int i = 0; i < portfolioDataGridView.Rows.Count; i++)
                {
                    try
                    {
                        // Daily Change Column ($)
                        if (GetDouble(portfolioDataGridView.Rows[i].Cells[4].Value.ToString()) > GetDouble("0.00"))
                            portfolioDataGridView.Rows[i].Cells[4].Style = new DataGridViewCellStyle { ForeColor = Color.Green };
                        else if (GetDouble(portfolioDataGridView.Rows[i].Cells[4].Value.ToString()) < GetDouble("0.00"))
                            portfolioDataGridView.Rows[i].Cells[4].Style = new DataGridViewCellStyle { ForeColor = Color.Red };
                        // Daily Change Column (%)
                        if (GetDouble(portfolioDataGridView.Rows[i].Cells[5].Value.ToString()) > GetDouble("0.00"))
                            portfolioDataGridView.Rows[i].Cells[5].Style = new DataGridViewCellStyle { ForeColor = Color.Green, Format = "P" };
                        else if (GetDouble(portfolioDataGridView.Rows[i].Cells[5].Value.ToString()) < GetDouble("0.00"))
                            portfolioDataGridView.Rows[i].Cells[5].Style = new DataGridViewCellStyle { ForeColor = Color.Red, Format = "P" };
                        // Unrealized Gain
                        if (GetDouble(portfolioDataGridView.Rows[i].Cells[8].Value.ToString()) > GetDouble("0.00"))
                            portfolioDataGridView.Rows[i].Cells[8].Style = new DataGridViewCellStyle { ForeColor = Color.Green };
                        else if (GetDouble(portfolioDataGridView.Rows[i].Cells[8].Value.ToString()) < GetDouble("0.00"))
                            portfolioDataGridView.Rows[i].Cells[8].Style = new DataGridViewCellStyle { ForeColor = Color.Red };
                        // Unrealized Gain Percent
                        if (GetDouble(portfolioDataGridView.Rows[i].Cells[9].Value.ToString()) > GetDouble("0.00"))
                            portfolioDataGridView.Rows[i].Cells[9].Style = new DataGridViewCellStyle { ForeColor = Color.Green, Format = "P" };
                        else if (GetDouble(portfolioDataGridView.Rows[i].Cells[9].Value.ToString()) < GetDouble("0.00"))
                            portfolioDataGridView.Rows[i].Cells[9].Style = new DataGridViewCellStyle { ForeColor = Color.Red, Format = "P" };

                       // double dailyChangePercent = 0, dailyChangeDollar = 0, unrealizedGainDouble = 0, unrealizedGainPercentDouble = 0;

                        // Daily Change ($)
                        //if (portfolioDataGridView.Rows[i].Cells[4].Value.ToString() != "")
                        //    Double.TryParse(portfolioDataGridView.Rows[i].Cells[4].Value.ToString(), out dailyChangeDollar);//.Substring(0, portfolioDataGridView.Rows[i].Cells[4].Value.ToString().Length - 1), out  dailyChangeDollar);
                        //// Daily Change (%)
                        //if (portfolioDataGridView.Rows[i].Cells[5].Value.ToString() != "")
                        //    Double.TryParse(portfolioDataGridView.Rows[i].Cells[5].Value.ToString().Substring(0, portfolioDataGridView.Rows[i].Cells[5].Value.ToString().Length - 1), out dailyChangePercent);
                        //// Unrealized Gains $ Amount
                        //if (portfolioDataGridView.Rows[i].Cells[8].Value.ToString() != "")
                        //    Double.TryParse(portfolioDataGridView.Rows[i].Cells[8].Value.ToString().Substring(0, portfolioDataGridView.Rows[i].Cells[8].Value.ToString().Length - 1), out unrealizedGainDouble);
                        //// Unrealized Gains %
                        //if (portfolioDataGridView.Rows[i].Cells[9].Value.ToString() != "")
                        //    Double.TryParse(portfolioDataGridView.Rows[i].Cells[9].Value.ToString().Substring(0, portfolioDataGridView.Rows[i].Cells[9].Value.ToString().Length - 1), out unrealizedGainPercentDouble);

                        // Daily Change Column ($)
                        //if (dailyChangeDollar > 0.00)
                        //    portfolioDataGridView.Rows[i].Cells[4].Style = new DataGridViewCellStyle { ForeColor = Color.Green };
                        //else if (dailyChangeDollar < 0.00)
                        //    portfolioDataGridView.Rows[i].Cells[4].Style = new DataGridViewCellStyle { ForeColor = Color.Red };
                        //// Daily Change Column (%)
                        //if (dailyChangePercent > 0.00)
                        //    portfolioDataGridView.Rows[i].Cells[5].Style = new DataGridViewCellStyle { ForeColor = Color.Green };
                        //else if (dailyChangePercent < 0.00)
                        //    portfolioDataGridView.Rows[i].Cells[5].Style = new DataGridViewCellStyle { ForeColor = Color.Red };
                        //// Unrealized Gain
                        //if (unrealizedGainDouble > 0.00)
                        //    portfolioDataGridView.Rows[i].Cells[8].Style = new DataGridViewCellStyle { ForeColor = Color.Green };
                        //else if (unrealizedGainDouble < 0.00)
                        //    portfolioDataGridView.Rows[i].Cells[8].Style = new DataGridViewCellStyle { ForeColor = Color.Red };
                        //// Unrealized Gain Percent
                        //if (unrealizedGainPercentDouble > 0.00)
                        //    portfolioDataGridView.Rows[i].Cells[9].Style = new DataGridViewCellStyle { ForeColor = Color.Green };
                        //else if (unrealizedGainPercentDouble < 0.00)
                        //    portfolioDataGridView.Rows[i].Cells[9].Style = new DataGridViewCellStyle { ForeColor = Color.Red };
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show("Error Message: " + e.ToString());
                    }

                }
            }
            else
                return;

            if (watchListDataGridView.Rows.Count > 0)
            {

                for (int i = 0; i < watchListDataGridView.Rows.Count; i++)
                {
                    try
                    {
                        double changeDollar, changePercent;


                        // Change ($)
                        Double.TryParse(watchListDataGridView.Rows[i].Cells[4].Value.ToString(), out changeDollar);//.Substring(0, watchListDataGridView.Rows[i].Cells[4].Value.ToString().Length - 1), out changeDollar);
                        // Change (%)
                        Double.TryParse(watchListDataGridView.Rows[i].Cells[5].Value.ToString().Substring(0, watchListDataGridView.Rows[i].Cells[5].Value.ToString().Length - 1), out changePercent);

                        // Change ($)
                        if (changeDollar > 0.00)
                            watchListDataGridView.Rows[i].Cells[4].Style = new DataGridViewCellStyle { ForeColor = Color.Green };
                        else if (changeDollar < 0.00)
                            watchListDataGridView.Rows[i].Cells[4].Style = new DataGridViewCellStyle { ForeColor = Color.Red };
                        // Change (%)
                        if (changePercent > 0.00)
                            watchListDataGridView.Rows[i].Cells[5].Style = new DataGridViewCellStyle { ForeColor = Color.Green };
                        else if (changePercent < 0.00)
                            watchListDataGridView.Rows[i].Cells[5].Style = new DataGridViewCellStyle { ForeColor = Color.Red };

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }
            }

        }

        /// <summary>
        /// Calculates totals for various columns in portfolio datagridview
        /// </summary>
        private void calculateTotals()
        {
            // If we find a totals row, delete it to make way for our new one
            for (int i = 0; i < portfolioDataGridView.Rows.Count; i++)
            {
                if (portfolioDataGridView.Rows[i].Cells[0].Value.ToString() == "Totals")
                    portfolioDataGridView.Rows.RemoveAt(i);
            }
            double bookValue = 0, temp1 = 0, temp2 = 0, marketValue = 0, unrealizedGainDollar = 0, gainInPercent = 0, dailyChange = 0;

            double bookValueOfAccounts = 37587.00;

            for (int i = 0; i < portfolioDataGridView.Rows.Count; i++)
            {
                // Daily Change
                Double.TryParse(portfolioDataGridView.Rows[i].Cells[4].Value.ToString(), out  temp1);
                Double.TryParse(portfolioDataGridView.Rows[i].Cells[2].Value.ToString(), out  temp2);
                dailyChange += temp1 * temp2;
                temp1 = 0;

                // Book Value
                Double.TryParse(portfolioDataGridView.Rows[i].Cells[6].Value.ToString(), out  temp1);
                bookValue += temp1;
                temp1 = 0;

                // Market Value
                Double.TryParse(portfolioDataGridView.Rows[i].Cells[7].Value.ToString(), out  temp1);
                marketValue += temp1;
                temp1 = 0;

                // Unrealized Gain ($)
                //Double.TryParse(portfolioDataGridView.Rows[i].Cells[8].Value.ToString(), out  temp1);
                //unrealizedGainDollar += temp1;
                //temp1 = 0;

                unrealizedGainDollar = marketValue - bookValueOfAccounts;
                gainInPercent = unrealizedGainDollar / bookValueOfAccounts * 100;
            }

            portfolioDataGridView.Rows.Add("Totals", "", "", "", dailyChange, "", bookValueOfAccounts, marketValue, unrealizedGainDollar, Math.Round(gainInPercent, 2) + "%", "");

            updateFontColors();
        }

        #endregion

        #region Timer

        // Initilizes the timer
        private void SetTimer()
        {
            timer.Tick += new EventHandler(timer_Tick_1);
            timer.Interval = 60000;
            timer.Start();
        }

        // Timer tick event
        private void timer_Tick_1(object sender, EventArgs e)
        {
            // If its past 4 or before 8, dont need to update
            if (DateTime.Now.Hour < 16 && DateTime.Now.Hour > 7)
                refreshButton2_Click(sender, e);
        }

        #endregion

        #region Open File Operations

        // Opens the holdings file and imports the data to the portfolioDataGridView
        private void openHoldingsFile()
        {
            createFolderStructure();

            try
            {
                var holdingsContents = File.ReadAllText(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Data", "Account Files", "Holdings.csv")).Split(new Char[] { '\n', ',' });

                if (holdingsContents.Length <= 1)
                {
                    MessageBox.Show("Accounts Totals file appears to have nothing in it, please check.");
                    return;
                }

                for (int i = 0; i < holdingsContents.Length; i += 4)
                {
                    if ((i + 3) < holdingsContents.Length && holdingsContents[i] != "CASH")
                        portfolioDataGridView.Rows.Add(holdingsContents[i], "", holdingsContents[i + 1], "", "", "", Convert.ToDouble(Convert.ToDouble(holdingsContents[i + 2]) * Convert.ToDouble(holdingsContents[i + 1])), "", "", "", holdingsContents[i + 3], "News", "Chart");
                    else if ((i + 3) < holdingsContents.Length && holdingsContents[i] == "CASH")
                        portfolioDataGridView.Rows.Add(holdingsContents[i], "", "", "", "", "", "", Convert.ToDouble(holdingsContents[i + 2]), "", "", holdingsContents[i + 3], "");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        #region Legacy Code
        /// <summary>
        /// Overloaded function that opens CSV file containing portfolio information
        /// *** Must be in .csv file format from webbroker ***
        /// </summary>
        /// <param name="file">The CSV file to be opened</param>
        //private void openCSVFile(string file)
        //{
        //    // Reading info from .csv
        //    var contents = File.ReadAllText(file).Split(',');

        //    // Adding account information to accounts datagridview
        //    //accountsDataGridView.Rows.Add(contents[1], contents[6].Substring(0, 15).TrimEnd(), Convert.ToDouble(contents[21]));

        //    // Checking file is not an old one
        //    if (Convert.ToDateTime(contents[1]) < mostRecentEditDate)
        //    {
        //        //MessageBox.Show("File is older than current version, will not load it");
        //        return;
        //    }

        //    // Changing label on main form
        //    lastEditDateLabel.Text = contents[1];

        //    // Setting starting position of .csv file for portfolio information
        //    int startingPostion = 38;

        //    // Deleting old account entries to make room for new ones
        //    CheckDataGridViewContents(contents[6].Substring(0, 7));

        //    // Looping through each row of data
        //    for (int i = 0; i < (contents.Length - 39) / 8; i++)
        //    {
        //        try
        //        {
        //            // If CSV file reads 0 shares, don't add it. It is a glitch when mutual funds are sold.
        //            if (Convert.ToDouble(contents[startingPostion + 2]) == 0)
        //            {
        //                continue;
        //            }

        //            // If name of security ends with FRAC, it is a mutual fund and add accordingly
        //            if (contents[startingPostion + 1].EndsWith("FRAC"))
        //            {
        //                MessageBox.Show(contents[startingPostion + 1] + " is detected as a mutual fund, which is not supported for real time updates.");
        //                portfolioDataGridView.Rows.Add(contents[startingPostion].Substring(contents[startingPostion].Length - 3), contents[startingPostion + 1], contents[startingPostion + 2], Convert.ToDouble(contents[startingPostion + 3]), "Unknown", "Unknown", Convert.ToDouble(contents[startingPostion + 4].ToString()), Convert.ToDouble(contents[startingPostion + 5]), Convert.ToDouble(contents[startingPostion + 6]), contents[startingPostion + 7] + "%", contents[6], "News");
        //            }
        //            else
        //            {
        //                portfolioDataGridView.Rows.Add(contents[startingPostion].Substring(contents[startingPostion].Length - 3), contents[startingPostion + 1], contents[startingPostion + 2], "", "", "", Convert.ToDouble(contents[startingPostion + 4].ToString()), "", "", "", contents[6], "News");
        //            }

        //        }
        //        catch (Exception ex)
        //        {
        //            MessageBox.Show(ex.Message);
        //        }

        //        startingPostion += 8;
        //    }

        //    mostRecentEditDate = Convert.ToDateTime(contents[1]);

        //    portfolioDataGridView.Rows.Add("Cash", "", "", "", "", "", Convert.ToDouble(contents[11]), Convert.ToDouble(contents[11]), "", "", contents[6], "");

        //    downloadPortfolioStockQuotes();

        //    updateFontColors();
        //}

        /// <summary>
        /// Opens CSV file containing portfolio information, opens a openfiledialog to specify which file
        /// </summary>
        //private void openFileDialog()
        //{
        //    string accountsFolderLocation = System.IO.Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Data", "Acccount Files");

        //    // String for extension comparison
        //    string ext = "";

        //    // Opening file dialog and checking if result is OK
        //    if (openCSVDialog.ShowDialog() == DialogResult.OK)
        //        ext = Path.GetExtension(openCSVDialog.FileName);
        //    else
        //        return;

        //    // If extension is not .csv, will exit method and display a message dialog
        //    if (ext != ".csv")
        //    {
        //        openCSVDialog.FileName = "";
        //        MessageBox.Show("File is not a CSV file, please select another.");
        //        return;
        //    }

        //    //if (!File.Exists(Path.Combine(accountsFolderLocation, openCSVDialog.SafeFileName)))
        //    //    copyCSVFile(openCSVDialog.FileName, openCSVDialog.SafeFileName);
        //    //else
        //    //{
        //    //    MessageBox.Show("You have already loaded this file!");
        //    //    return;
        //    //}

        //    //openCSVFile(openCSVDialog.FileName);
        //}

        // Opens accounts file and processes info
        #endregion

        private void openAccountTotalsFiles()
        {
            createFolderStructure();

            try
            {

                //XDocument doc = XDocument.Load(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Data", "Account Files", "AccountTotals.xml"));

                //XElement results = doc.Root.Element("AllAccounts");

                //results.

                var accountAllContents = File.ReadAllText(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Data", "Account Files", "AccountTotals.csv")).Split(new Char[] { '\n', ',' });
                var accountTFSAContents = File.ReadAllText(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Data", "Account Files", "TFSATotals.csv")).Split(new Char[] { '\n', ',' });
                var accountRRSPContents = File.ReadAllText(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Data", "Account Files", "RRSPTotals.csv")).Split(new Char[] { '\n', ',' });
                
                //XmlWriterSettings settings = new XmlWriterSettings();
                //settings.Indent = true;
                //settings.IndentChars = ("    ");
                //settings.CloseOutput = true;
                //settings.OmitXmlDeclaration = true;
                //settings.ConformanceLevel = ConformanceLevel.Auto;

                //using (XmlWriter writer = XmlWriter.Create("Test.xml", settings))
                //{

                //    for (int i = 0; i < accountContents.Length / 2; i+=2)
                //    {
                //        writer.WriteStartElement("AllAccounts");
                //        writer.WriteElementString("Date", accountContents[i]);
                //        writer.WriteElementString("Amount", accountContents[i + 1]);
                //        writer.WriteEndElement();
                //    }
                //    writer.Flush();
                //}

                if (accountAllContents.Length <= 1)
                {
                    MessageBox.Show("Accounts Totals file appears to have nothing in it, please check.");
                    return;
                }

                for (int i = 0; i < accountAllContents.Length; i += 2)
                {
                    if ((i + 1) < accountAllContents.Length)
                        accountsAllDataGridView.Rows.Add(Convert.ToDateTime(accountAllContents[i]), Convert.ToDouble(accountAllContents[i + 1]));
                }

                //for (int i = 0; i < accountTFSAContents.Length; i += 2)
                //{
                //    if ((i + 1) < accountAllContents.Length)
                //        accountsTFSADataGridView.Rows.Add(Convert.ToDateTime(accountTFSAContents[i]), Convert.ToDouble(accountTFSAContents[i + 1]));
                //}

                //for (int i = 0; i < accountRRSPContents.Length; i += 2)
                //{
                //    if ((i + 1) < accountRRSPContents.Length)
                //        accountsRRSPDataGridView.Rows.Add(Convert.ToDateTime(accountRRSPContents[i]), Convert.ToDouble(accountRRSPContents[i + 1]));
                //}

                #region Legacy Code
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        #endregion

        #region Valiadation

        ///// <summary>
        ///// Checks the portfolio datagridview contents, and deletes any entries with accountName under the account column. This is to clean up the old values when updating with a new CSV file.
        ///// </summary>
        ///// <param name="accountName">The account name of the currently importing account</param>
        //private void CheckDataGridViewContents(string accountName)
        //{
        //    List<int> rowIndexes = new List<int>();

        //    foreach (DataGridViewRow row in portfolioDataGridView.Rows)
        //    {
        //        if (row.Cells[10].Value.ToString() != "")
        //        {
        //            if (row.Cells[10].Value.ToString().Substring(0, 7) == accountName)
        //                rowIndexes.Add(row.Index);
        //        }
        //    }

        //    for (int i = rowIndexes.Count - 1; i >= 0; i--)
        //        portfolioDataGridView.Rows.RemoveAt(rowIndexes[i]);
        //}

        /// <summary>
        /// Checks if a record in the accountDataGridView is equal to the date passed in
        /// </summary>
        /// <param name="date">The date we are looking for</param>
        /// <returns>True if value is found, false if not found</returns>
        private Boolean checkDatesInAccounts(DateTime date)
        {
            if (accountsAllDataGridView.Rows.Count > 1)
            {
                for (int i = 0; i < accountsAllDataGridView.Rows.Count; i++)
                {
                    if (Convert.ToDateTime(accountsAllDataGridView.Rows[i].Cells[0].Value.ToString()) == date)
                        return true;
                }
            }

            return false;
        }

        // Adds current total to the accounts file
        private void addTotalToAccountsTotalsFile()
        {
            if (!File.Exists(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Data", "Account Files", "AccountTotals.csv")) || !File.Exists(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Data", "Account Files", "TFSATotals.csv")) || !File.Exists(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Data", "Account Files", "RRSPTotals.csv")))
            {
                MessageBox.Show("Account totals files not found!");
            }
            else
            {
                double totalTFSA = 0;
                double totalRRSP = 0;

                for (int i = 0; i < accountsAllDataGridView.Rows.Count-2; i++)
                {
                    if (portfolioDataGridView.Rows[i].Cells[10].Value.ToString() == "TFSA")
                         totalTFSA += Convert.ToDouble(portfolioDataGridView.Rows[10].Cells[10].Value);
                    if (portfolioDataGridView.Rows[i].Cells[10].Value.ToString() == "RRSP")
                         totalRRSP += Convert.ToDouble(portfolioDataGridView.Rows[10].Cells[10].Value);
                }
                using (StreamWriter sw = File.AppendText(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Data", "Account Files", "AccountTotals.csv")))
                {
                    sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy") + "," + portfolioDataGridView.Rows[portfolioDataGridView.Rows.Count - 1].Cells[7].Value);
                }
                using (StreamWriter sw = File.AppendText(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Data", "Account Files", "TFSATotals.csv")))
                {
                    sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy") + "," + totalTFSA.ToString());
                }
                using (StreamWriter sw = File.AppendText(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Data", "Account Files", "RRSPTotals.csv")))
                {
                    sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy") + "," + totalRRSP.ToString());
                }

                notifyIcon.BalloonTipTitle = "Portfolio Tracker";
                notifyIcon.BalloonTipText = "Added " + portfolioDataGridView.Rows[portfolioDataGridView.Rows.Count - 1].Cells[7].Value + " for todays value";
                notifyIcon.ShowBalloonTip(500);
            }
        }

        // Checking for internet connection
        public static bool CheckForInternetConnection()
        {
            try
            {
                using (var client = new WebClient())
                using (var stream = client.OpenRead("http://www.google.com"))
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        private static double? GetDouble(string input)
        {
            if (input == null) return null;

            input = input.Replace("%", "");

            double value;

            if (Double.TryParse(input, out value)) return value;
            return null;
        }

        private void portfolioDataGridView_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
        {
            if (e.CellValue1.GetType() != typeof(double) || e.CellValue2.GetType() != typeof(double))
            {
                //e.SortResult = 0;
                e.Handled = true;
            }
        }

        #endregion

        #region Button Events

        // Graph Button Click Event
        private void graphButton_Click(object sender, EventArgs e)
        {
            List<DateTime> dates = new List<DateTime>();
            List<Double> values = new List<Double>();

            DateTime tempDate;
            Double tempDouble;

            for (int i = 0; i < accountsAllDataGridView.Rows.Count; i++)
            {
                DateTime.TryParse(accountsAllDataGridView.Rows[i].Cells[0].Value.ToString(), out tempDate);
                dates.Add(tempDate);
                Double.TryParse(accountsAllDataGridView.Rows[i].Cells[1].Value.ToString(), out tempDouble);
                values.Add(tempDouble);
            }

            GraphForm newForm = new GraphForm(dates, values);

            newForm.Show();
        }

        // Open watch list button click event
        private void openWatchListButton_Click(object sender, EventArgs e)
        {
            string watchListFileLocation = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Data", "Watch List", "WatchList.csv");

            if (File.Exists(watchListFileLocation))
                Process.Start(watchListFileLocation);
            else
            {
                File.Create(watchListFileLocation);
                Process.Start(watchListFileLocation);
            }
        }

        // Refresh button click event
        private void refreshButton2_Click(object sender, EventArgs e)
        {
            // Checking for Internet Connection
            if (!CheckForInternetConnection())
            {
                MessageBox.Show("No internet connection detected.");
                return;
            }

            portfolioDataGridView.Rows.Clear();
            accountsAllDataGridView.Rows.Clear();

            // Opens account totals file
            openAccountTotalsFiles();

            // Opens Holdings File
            openHoldingsFile();

            // Downloading watch list stock quotes
            downloadWatchListStockQuotes();

            // Downloading Portfolio Stock Information
            downloadPortfolioStockQuotes();

            // Calculating totals in portfolio datagridview
            calculateTotals();

            // Adding total to accounts file
            if (!checkDatesInAccounts(DateTime.Now.Date) && DateTime.Now.Hour > 14 && DateTime.Now.DayOfWeek != DayOfWeek.Saturday && DateTime.Now.DayOfWeek != DayOfWeek.Sunday)
            {
                addTotalToAccountsTotalsFile();
            }

            // Changing last update label
            if (DateTime.Now.Hour > 12)
                lastUpdateLabel.Text = DateTime.Now.ToString("HH:mm:ss") + " PM";
            else
                lastUpdateLabel.Text = DateTime.Now.ToString("HH:mm:ss") + " AM";

        }

        // Opens holdings file to edit
        private void modifyHoldingsButton_Click(object sender, EventArgs e)
        {
            string holdingsListFileLocation = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Data", "Account Files", "Holdings.csv");

            if (File.Exists(holdingsListFileLocation))
                Process.Start(holdingsListFileLocation);
            else
            {
                File.Create(holdingsListFileLocation);
                Process.Start(holdingsListFileLocation);
            }
        }

        // Opens Account Totals file to edit
        private void modifyAccountTotalsButton_Click(object sender, EventArgs e)
        {
            string accountsListFileLocation = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Data", "Account Files", "AccountTotals.csv");

            if (File.Exists(accountsListFileLocation))
                Process.Start(accountsListFileLocation);
            else
            {
                File.Create(accountsListFileLocation);
                Process.Start(accountsListFileLocation);
            }
        }

        #endregion

        #region Portfolio DataGridView Events

        // Portfolio Button Click Event
        private void portfolioDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {

            if (e.RowIndex >= 0 && ((DataGridView)sender).Columns[e.ColumnIndex].GetType() == typeof(DataGridViewButtonColumn))
            {
                // News Button
                if (e.ColumnIndex == 11)
                {
                    string fileLocation = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Data", "News List", portfolioDataGridView.Rows[e.RowIndex].Cells[0].Value.ToString() + ".xml");

                    try
                    {
                        string beginDownloadURL = "http://feeds.finance.yahoo.com/rss/2.0/headline?s="; // EX: http://feeds.finance.yahoo.com/rss/2.0/headline?s=FTT.TO&region=CA
                        string middleDownloadURL = portfolioDataGridView.Rows[e.RowIndex].Cells[0].Value.ToString();
                        string endURL = "&region=CA";

                        using (WebClient webClient = new WebClient())
                        {
                            webClient.DownloadFile(beginDownloadURL + middleDownloadURL + endURL, fileLocation);
                        }

                        XDocument xmlDoc = XDocument.Load(fileLocation);
                        var titles = xmlDoc.Descendants("item").Elements("title").ToArray();
                        var links = xmlDoc.Descendants("item").Elements("link").ToArray();
                        var dates = xmlDoc.Descendants("item").Elements("pubDate").ToArray();

                        if (dates.Count() < 1)
                        {
                            MessageBox.Show("No news found");
                            return;
                        }

                        List<System.Xml.Linq.XElement> titlesList = new List<System.Xml.Linq.XElement>();
                        List<System.Xml.Linq.XElement> datesList = new List<System.Xml.Linq.XElement>();
                        List<System.Xml.Linq.XElement> linksList = new List<System.Xml.Linq.XElement>();

                        for (int i = 0; i < titles.Count(); i++)
                        {
                            titlesList.Add(titles[i]);
                            datesList.Add(dates[i]);
                            linksList.Add(links[i]);
                        }

                        NewsForm newsForm = new NewsForm(datesList, titlesList, linksList);

                        newsForm.Show();

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }

                // Chart Button
                if (e.ColumnIndex == 12)
                {
                    ChartRequestForm chartForm = new ChartRequestForm(portfolioDataGridView.Rows[e.RowIndex].Cells[0].Value.ToString());

                    chartForm.ShowDialog();
                }
            }
        }

        // Event when sort mode is changed on a column in portfolio DataGridView
        private void portfolioDataGridView_ColumnSortModeChanged(object sender, DataGridViewColumnEventArgs e)
        {
            //DataGridView dgv_copy = new DataGridView(); 
 
            //if (dgv_copy.Columns.Count == 0)  
            //{  
            //    foreach (DataGridViewColumn dgvc in portfolioDataGridView.Columns)  
            //    {  
            //        dgv_copy.Columns.Add(dgvc.Clone() as DataGridViewColumn);
            //    }
            //}

            //for (int i = 0; i < portfolioDataGridView.Rows.Count - 1; i++)
            //    if (portfolioDataGridView.Rows[i].Cells[0].Value.ToString() == "CASH" || portfolioDataGridView.Rows[i].Cells[0].Value.ToString() == "Totals")
            //        portfolioDataGridView.Rows.RemoveAt(i); 
                
                    //dgv_copy.Rows.Add()
                    
                    //DataGridViewRow test = portfolioDataGridView.Rows[i];
                
        }

        // Event when finished sorting column in portfolio DataGridView
        private void portfolioDataGridView_Sorted(object sender, EventArgs e)
        {
            //calculateTotals();
        }

        #endregion

        #region Watch List DataGridView Events

        // Watch List DataGridView button click event for news
        private void watchListDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && ((DataGridView)sender).Columns[e.ColumnIndex].GetType() == typeof(DataGridViewButtonColumn))
            {
                // News Button
                if (e.ColumnIndex == 6)
                {
                    string fileLocation = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Data", "News List", watchListDataGridView.Rows[e.RowIndex].Cells[0].Value.ToString() + ".xml");

                    try
                    {
                        string beginDownloadURL = "http://feeds.finance.yahoo.com/rss/2.0/headline?s="; // EX: http://feeds.finance.yahoo.com/rss/2.0/headline?s=FTT.TO&region=CA
                        string middleDownloadURL = watchListDataGridView.Rows[e.RowIndex].Cells[0].Value.ToString();
                        string endURL = "&region=CA";

                        using (WebClient webClient = new WebClient())
                        {
                            webClient.DownloadFile(beginDownloadURL + middleDownloadURL + endURL, fileLocation);
                        }

                        XDocument xmlDoc = XDocument.Load(fileLocation);
                        var titles = xmlDoc.Descendants("item").Elements("title").ToArray();
                        var links = xmlDoc.Descendants("item").Elements("link").ToArray();
                        var dates = xmlDoc.Descendants("item").Elements("pubDate").ToArray();

                        if (dates.Count() < 1)
                        {
                            MessageBox.Show("No news found");
                            return;
                        }

                        List<System.Xml.Linq.XElement> titlesList = new List<System.Xml.Linq.XElement>();
                        List<System.Xml.Linq.XElement> datesList = new List<System.Xml.Linq.XElement>();
                        List<System.Xml.Linq.XElement> linksList = new List<System.Xml.Linq.XElement>();

                        for (int i = 0; i < titles.Count(); i++)
                        {
                            titlesList.Add(titles[i]);
                            datesList.Add(dates[i]);
                            linksList.Add(links[i]);
                        }

                        NewsForm newsForm = new NewsForm(datesList, titlesList, linksList);

                        newsForm.Show();

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                // Chart Button
                if (e.ColumnIndex == 7)
                {
                    ChartRequestForm chartForm = new ChartRequestForm(watchListDataGridView.Rows[e.RowIndex].Cells[0].Value.ToString());

                    chartForm.Show();
                }
            }

        }

        #endregion

        #region "Minimizing"

        private void MainForm_Resize(object sender, EventArgs e)
        {
            //if (FormWindowState.Minimized == this.WindowState)
            //{
            //    notifyIcon.Visible = true;
            //    notifyIcon.BalloonTipTitle = "Portfolio Tracker";
            //    notifyIcon.BalloonTipText = "Portfolio Tracker has been minimized to tray.";
            //    notifyIcon.ShowBalloonTip(500);
            //    this.Hide();
            //}
            //else if (FormWindowState.Normal == this.WindowState)
            //{
            //    notifyIcon.Visible = false;
            //}
        }

        private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            //this.Show();
            //this.WindowState = FormWindowState.Normal;
        }

        #endregion
    }
}